﻿using Microsoft.Practices.Prism.StoreApps;
using Microsoft.Practices.Prism.StoreApps.Interfaces;
using System;
using WinRT.SIP.UILogic.Models;
using WinRT.SIP.UILogic.Repositories;

namespace WinRT.SIP.UILogic.ViewModels
{
    public class CredentialsFlyoutViewModel : BindableBase, IFlyoutViewModel
    {
        private ICredentialsRepository _credentialsRepository;
        private Action _closeFlyout;
        private Action _goBack;

        private string _displayName;
        private string _privateIdentity;
        private string _publicIdentity;
        private string _password;

        public DelegateCommand GoBackCommand { get; private set; }
        public DelegateCommand SaveCommand { get; private set; }

        public Action CloseFlyout
        {
            get { return _closeFlyout; }
            set { SetProperty(ref _closeFlyout, value); }
        }

        public Action GoBack
        {
            get { return _goBack; }
            set { SetProperty(ref _goBack, value); }
        }

        public string DisplayName
        {
            get { return _displayName; }
            set { SetProperty(ref _displayName, value); }
        }

        public string PrivateIdentity
        {
            get { return _privateIdentity; }
            set { SetProperty(ref _privateIdentity, value); }
        }

        public string PublicIdentity
        {
            get { return _publicIdentity; }
            set { SetProperty(ref _publicIdentity, value); }
        }

        public string Password
        {
            get { return _password; }
            set { SetProperty(ref _password, value); }
        }

        public async void Open(object parameter, Action successAction)
        {
            var credentials = await _credentialsRepository.LoadAsync();
            if (credentials != null)
            {
                DisplayName = credentials.DisplayName;
                PrivateIdentity = credentials.PrivateIdentity;
                PublicIdentity = credentials.PublicIdentity;
                Password = credentials.Password;
            }
        }

        public CredentialsFlyoutViewModel(ICredentialsRepository credentialsRepository)
        {
            _credentialsRepository = credentialsRepository;

            GoBackCommand = new DelegateCommand(() => GoBack());
            SaveCommand = new DelegateCommand(async () =>
                {
                    CloseFlyout();
                    await _credentialsRepository.SaveAsync(new Credentials
                    {
                        DisplayName = _displayName,
                        PrivateIdentity = _privateIdentity,
                        PublicIdentity = _publicIdentity,
                        Password = _password
                    });
                });
        }
    }
}
